//
//  UIViewController+Swizzling.swift
//  HeadlineNews
//
//  Created by han on 2019/7/31.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

private var isSwizzled = false
// 静默更换Icon
extension UIViewController {
    
    class func initializeMethod() {
        if self != UIViewController.self {
            return
        }
        
        // 保证只执行一次
        if isSwizzled {
            return 
        }
        isSwizzled = true
        let originalSelector = #selector(UIViewController.present(_:animated:completion:))
        let swizzledSelector = #selector(UIViewController.swizzled_present(_:animated:completion:))
        
        let originalMethod = class_getInstanceMethod(self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
        //在进行 Swizzling 的时候,需要用 class_addMethod 先进行判断一下原有类中是否有要替换方法的实现
        let didAddMethod: Bool = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
        //如果 class_addMethod 返回 yes,说明当前类中没有要替换方法的实现,所以需要在父类中查找,这时候就用到 method_getImplemetation 去获取 class_getInstanceMethod 里面的方法实现,然后再进行 class_replaceMethod 来实现 Swizzing
        if didAddMethod {
            class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
        } else {
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
        }
        
    }
    @objc func swizzled_present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
        // 在这里判断是否是更换icon时的弹出框
        if viewControllerToPresent is UIAlertController {
            
            let alertTitle = (viewControllerToPresent as! UIAlertController).title
            let alertMessage = (viewControllerToPresent as! UIAlertController).message
            
            // 更换icon时的弹出框，这两个string都为nil。
            if alertTitle == nil && alertMessage == nil {
                return
            }
        }
        // 因为方法已经交换，这个地方的调用就相当于调用原先系统的 present
        self.swizzled_present(viewControllerToPresent, animated: flag, completion: completion)
    }
}

